import copy
import json
import matplotlib.pyplot as plt

'''
根据日志生成测试数据
'''

import tkinter as tk
from tkinter import filedialog, messagebox
import json
redis_need_key_list = ['currentSpeed', 'posX1', 'posY1', 'agvDir1', 'IsLift', 'liftHeight']
def read_log(file_path, data_type, data_key):
    json_list = []
    pre_data = ''
    key_dict = {
        'redis': 'RedisData',
        'mqtt': 'MqttData',
        's7': 'S7Data'
    }

    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                if data_type == 'redis':
                    if '接收到Redis数据' not in line:
                        continue
                    try:
                        line = line[42:]
                        json_object = json.loads(line)
                        cur_data = json_object[data_key]
                        listen_data = {}
                        for redis_key in redis_need_key_list:
                            listen_data[redis_key] = cur_data[redis_key]
                        listen_data_str = json.dumps(listen_data)
                    except Exception as e:
                        print(line)
                elif data_type == 'mqtt':
                    if 'Payload' not in line:
                        continue
                    line = line[38:]
                    json_object = json.loads(line)
                    cur_data = json_object[data_key]
                    listen_data_str = json.dumps(cur_data)
                elif data_type == 's7':
                    if data_key not in line:
                        continue
                    start_index = line.index(data_key)
                    line = line[start_index + len(data_key) + 3:]
                    listen_data_str = line
                    cur_data = json.loads(line)
                if pre_data == listen_data_str:
                    continue
                pre_data = listen_data_str
                temp = {
                    key_dict[data_type]: {data_key : cur_data}
                }
                json_list.append(temp)

        with open('result/result.json', 'w', encoding='utf-8') as file:
            json.dump(json_list, file, indent=4, ensure_ascii=False)

        messagebox.showinfo("成功", "数据已提取并保存到 result.json")
    except Exception as e:
        messagebox.showerror("错误", f"处理文件时出错: {e}")

def select_file():
    file_path = filedialog.askopenfilename(title="选择文件")
    if file_path:
        file_path_entry.delete(0, tk.END)
        file_path_entry.insert(0, file_path)

def submit():
    file_path = file_path_entry.get()
    data_type = data_type_var.get()
    data_key = data_key_entry.get()

    if not file_path:
        messagebox.showerror("错误", "请先选择文件路径！")
        return

    if data_type not in ['redis', 's7', 'mqtt']:
        messagebox.showerror("错误", "请选择有效的数据类型！")
        return

    if data_key is None or data_key == '':
        messagebox.showerror("错误", "请输入有效的数据key值！")
        return

    read_log(file_path, data_type, data_key)

# 创建主窗口
root = tk.Tk()
root.title("日志数据提取工具")

# 文件路径选择
tk.Label(root, text="文件路径:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
file_path_entry = tk.Entry(root, width=50)
file_path_entry.grid(row=0, column=1, padx=5, pady=5)
file_select_button = tk.Button(root, text="选择文件", command=select_file)
file_select_button.grid(row=0, column=2, padx=5, pady=5)

# 数据类型选择
tk.Label(root, text="数据类型:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
data_type_var = tk.StringVar(value="redis")
data_type_menu = tk.OptionMenu(root, data_type_var, "redis", "s7", "mqtt")
data_type_menu.grid(row=1, column=1, padx=5, pady=5, sticky="w")

# key值
tk.Label(root, text="字段key值:").grid(row=2, column=0, padx=5, pady=5, sticky="w")
data_key_entry = tk.Entry(root, width=50)
data_key_entry.grid(row=2, column=1, padx=5, pady=5)

# 提交按钮
submit_button = tk.Button(root, text="提交", command=submit)
submit_button.grid(row=3, column=0, columnspan=3, pady=10)

# 启动主循环
root.mainloop()
